const Dynamic = require("../model/dynamic_model");
const User = require("../model/user_model");
const mongoose = require("mongoose");

exports.addDynamicApi = async (dynamic) => {
  return new Dynamic({
    ...dynamic,
  }).save();
};

exports.getFriendsDynamicApi = async (_id) => {
  return await User.aggregate([
    { $match: { _id: mongoose.Types.ObjectId(_id) } },
    {
      $lookup: {
        from: "dynamic",
        localField: "good_friends",
        foreignField: "dynamic_creator_id",
        as: "dynamics",
      },
    },
    {
      $sort: {
        "dynamics.dynamic_date": -1,
      },
    },
  ]);
};

exports.getDynamicApi = async (_id) => {
  return await Dynamic.find({ dynamic_creator_id: _id }).sort({dynamic_date:-1});
};


exports.getNewDynamicNumApi = async (_id) => {
    return await User.aggregate([
      { $unwind: "$good_friends"},
      { $match: { _id: mongoose.Types.ObjectId(_id) }},
      { $lookup: { from: "dynamic",  localField: "good_friends",foreignField: "dynamic_creator_id", as: "dynamics"},},
      { $project: { _id: 0, qq_account: 0, nick_name: 0, good_friends: 0, "dynamics._id": 0, "dynamics.dynamic_date": 0, "dynamics.dynamic_content": 0, "dynamics.dynamic_title": 0, "dynamics.dynamic_user_avatar": 0, "dynamics.dynamic_imgs": 0,"dynamics.dynamic_new": 0} },
      { $unwind: { path: "$dynamics"}},
      { $match: { "dynamics.dynamic_read_friends": { $nin: [_id]}}},
      { $group: { _id: "$dynamics.dynamic_creator_id", count: { $sum: 1 }}},
      { $count: "new_dynamic_nums"}
    ]);
  };

exports.updateDynamicsReadStatus = async (_id) => {
  const ids = [];
  const dynamicIds = await User.aggregate([
    { $unwind: "$good_friends",},
    { $match: { _id: mongoose.Types.ObjectId(_id) }},
    { $lookup: { from: "dynamic", localField: "good_friends", foreignField: "dynamic_creator_id", as: "dynamics",}},
    { $project: { _id: 0,qq_account: 0,nick_name: 0,line_status: 0,good_friends: 0,"dynamics.dynamic_date": 0,"dynamics.dynamic_content": 0,"dynamics.dynamic_title": 0,"dynamics.dynamic_user_avatar": 0,"dynamics.dynamic_imgs": 0,"dynamics.dynamic_new": 0,}},
    { $unwind: "$dynamics"},
    { $match: { "dynamics.dynamic_read_friends": { $nin: [_id]}}},
    { $group: { _id: "$dynamics", freights: { $addToSet: "$dynamics._id" } }},
    { $project: { _id: 0 }},
   ]);
   dynamicIds.forEach(v=>ids.push(v.freights[0].toHexString()))
   return await Dynamic.updateMany({_id:{ $in:ids }}, {$addToSet:{ dynamic_read_friends:_id }})
};
